<template>
  <div class="assignment-container">
    <Breadcrumb>
      <template #bread-right>
        <div class="tool-btn flex">
          <ClassSelector v-model:currentClass="currentClass" :show-all="true" />
          <el-date-picker
            v-model="searchDate"
            style="width: 1.2rem"
            placeholder="请选择日期"
            :suffix-icon="Calendar"
          />
          <el-input
            v-model="searchValue"
            style="width: 1.2rem"
            placeholder="请输入任务名称"
            :suffix-icon="Search"
          />
        </div>
      </template>
    </Breadcrumb>

    <main class="content flex">
      <div class="content-left">
        <el-tabs
          v-model="taskType"
          @tab-change="onTabChange"
          class="assignment-tabs"
        >
          <el-tab-pane label="已发布任务" name="1"></el-tab-pane>
          <el-tab-pane label="待发布任务" name="0"></el-tab-pane>
        </el-tabs>
        <el-empty v-show="!taskList.length" v-loading="loading"></el-empty>
        <ul>
          <li
            class="content-item flex-between"
            v-for="(task, index) in taskList"
            :key="index"
          >
            <div class="content-item-left hover" @click="toDetail(task)">
              <div class="flex title">
                <el-tag type="success" class="tag">{{
                  TaskTypeMap[task.task_type].title
                }}</el-tag>
                <el-tag
                  v-if="task.wrong_question_task"
                  class="tag"
                  :class="getIsRetrainTag(task) ? 'retrained' : 'not-retrain'"
                >
                  重练
                </el-tag>
                <div class="task-name text-ellipsis" :title="task.task_name">
                  {{ task.task_name }}
                </div>
              </div>
              <div class="info flex">
                <div class="info-item flex">
                  <img
                    src="@/assets/images/assignment/user.png"
                    class="icon-img"
                    alt=""
                    srcset=""
                  />

                  {{
                    task.class_info &&
                    task.class_info.map(item => item.class_name).join('、')
                  }}
                </div>
                <div class="info-item flex">
                  <img
                    src="@/assets/images/assignment/clock.png"
                    class="icon-img"
                    alt=""
                    srcset=""
                  />

                  截止：{{ dayjs(task.deadline).format('MM/DD HH:mm') }}
                </div>
              </div>
            </div>
            <!-- 已发布任务 -->
            <div class="content-item-right flex" v-if="taskType === '1'">
              <div class="right-1">
                <div class="tip">正确率</div>
                <div class="right-rate" :style="{ color: getColor(task) }">
                  {{
                    Number(task.grade_count)
                      ? parseFloat((task.score_rate * 100).toFixed(1)) + '%'
                      : '--'
                  }}
                </div>
              </div>
              <div class="right-2 flex-column">
                <div class="tip finish">
                  <img
                    src="@/assets/images/assignment/user-icon.png"
                    class="small-icon-img"
                    alt=""
                    srcset=""
                  />
                  提交：{{ task.completed_student }}/{{ task.total_student }}
                  <el-dropdown class="more-btn">
                    <el-icon>
                      <MoreFilled />
                    </el-icon>
                    <template #dropdown>
                      <el-dropdown-menu>
                        <el-dropdown-item @click="openDialog(task.task_id)">
                          删除
                        </el-dropdown-item>
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                </div>
                <div class="flex right-2-btn-list">
                  <div
                    class="correct-btn"
                    :style="{
                      cursor: task.status === 1 ? 'pointer' : 'default',
                      color: task.status === 1 ? '#5466e7' : '#b7b8bb'
                    }"
                    @click="toCorrect(task)"
                  >
                    <img
                      v-if="task.status === 1"
                      class="correct-icon small-icon-img"
                      src="@/assets/images/assignment/corrected-icon.png"
                    />
                    <img
                      class="correct-icon small-icon-img"
                      src="@/assets/images/assignment/pending-correct.png"
                      v-else
                    />
                    {{ CORRECT_STATUS[task.status] }}
                  </div>
                </div>
              </div>
            </div>
            <!-- 待发布任务 -->
            <div class="content-item-right flex" v-else>
              <div
                class="correct-btn hover"
                style="color: #5466e7"
                @click="toEdit(task)"
              >
                <img
                  class="correct-icon small-icon-img"
                  src="@/assets/images/assignment/publish.png"
                />
                发布
              </div>
              <el-popconfirm
                title="确认删除吗？"
                @confirm="onDelete(task.task_id)"
              >
                <template #reference>
                  <div class="correct-btn hover" style="color: #f07b61">
                    <img
                      class="correct-icon small-icon-img"
                      src="@/assets/images/assignment/delete-icon.png"
                    />
                    删除
                  </div>
                </template>
              </el-popconfirm>
            </div>
          </li>
        </ul>
        <el-pagination
          v-if="taskList.length"
          layout="prev, pager, next"
          v-model:current-page="pageInfo.pageIndex"
          :page-size="pageInfo.pageSize"
          :total="pageInfo.total"
          @change="getTaskListInfo"
        />
      </div>
      <div class="content-right">
        <div class="border"></div>
        <div class="content-right">
          <div class="title">新建任务</div>
          <div class="btn-list flex">
            <div class="right-item flex-column hover" @click="toCourse">
              <img
                src="@/assets/images/assignment/course.png"
                class="item-img"
              />
              <span>课程任务</span>
            </div>
            <div class="right-item flex-column hover" @click="toPractice">
              <img
                src="@/assets/images/assignment/practice.png"
                class="item-img"
              />
              <span>习题任务</span>
            </div>
            <!-- <div class="right-item flex-column hover" @click="toTask">
              <img
                src="@/assets/images/assignment/target.png"
                class="item-img"
              />
              <span>错题任务</span>
            </div> -->
          </div>
          <el-divider />
          <div class="btn-list flex">
            <div class="right-item flex-column hover" @click="onShowFinish">
              <img
                src="@/assets/images/assignment/finish-statistics.png"
                class="item-img"
              />
              <span>完成统计</span>
            </div>
            <div class="right-item flex-column hover" @click="toWrongScan">
              <img
                src="@/assets/images/assignment/wrong-scan.png"
                class="item-img"
              />
              <span>错题反扫</span>
            </div>
          </div>
        </div>
      </div>
    </main>
  </div>
  <TaskDrawer :task-id="editTaskId" v-if="taskVis" v-model:visible="taskVis" />
  <!-- 完成统计抽屉 -->
  <FinishDrawer v-if="isFinish" v-model:isShow="isFinish" />
  <el-dialog v-model="dialogVisible" title="删除提示" class="delete-dialog">
    <span>请确认是否删除作业任务</span>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="onDelete(deleteTaskId)">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, watch, onMounted, onUnmounted, nextTick } from 'vue'
import Breadcrumb from '@/components/Breadcrumb.vue'
import { Calendar, Search, MoreFilled } from '@element-plus/icons-vue'
import router from '@/router'
import { getTaskList, postCollect, deleteTask } from '@/apis/assignment/index'
import { useAuthStore } from '@/stores'
import dayjs from 'dayjs'
import { TaskTypeMap } from '@/stores/task'
import { debounce } from '@/utils/debounce.js'
import ClassSelector from './components/ClassSelector.vue'
import { ElMessage } from 'element-plus'
import TaskDrawer from '@/components/publish-task/TaskDrawer.vue'
import { storeToRefs } from 'pinia'
import FinishDrawer from './components/FinishDrawer.vue'
import { useRoute } from 'vue-router'
import { CORRECT_TYPE } from './single-correct/data'

const CORRECT_STATUS = {
  0: '未提交',
  1: '待批改',
  2: '已完成'
}

const route = useRoute()
const searchDate = ref()
const searchValue = ref()
const taskType = ref('1')
const taskList = ref([])
const pageInfo = ref({
  total: 0,
  pageSize: 10,
  pageIndex: 1
})
const loading = ref(false)
const dialogVisible = ref(false)
const deleteTaskId = ref('')

const authStore = useAuthStore()
const { nowGlobalSubjectId, nowGlobalRole, nowGlobalStageId } =
  storeToRefs(authStore)

const openDialog = id => {
  deleteTaskId.value = id
  dialogVisible.value = true
}
const onTabChange = () => {
  taskList.value = []
  onSearch()
}
const onSearch = () => {
  pageInfo.value = {
    total: 0,
    pageSize: 10,
    pageIndex: 1
  }
  getTaskListInfo()
}
const currentClass = ref()

watch(
  [
    () => nowGlobalSubjectId.value,
    () => nowGlobalRole.value,
    () => nowGlobalStageId.value,
    () => searchDate.value,
    () => searchValue.value,
    () => currentClass.value,
    () => taskType.value
  ],
  () => {
    debounce(() => {
      onSearch()
    }, 500)
  }
)

const onDelete = async task_id => {
  const res = await deleteTask({
    task_id
  })

  onSearch()
  if (res.code === 1) {
    ElMessage.success('删除成功')
  }
  dialogVisible.value = false
}

// 获取任务列表
const getTaskListInfo = async () => {
  let param = {
    teacher_id: authStore.userInfo.userId,
    task_name: searchValue.value,
    page: pageInfo.value.pageIndex,
    page_size: pageInfo.value.pageSize,
    class_id: currentClass.value?.[1],
    class_type: currentClass.value?.[1] ? currentClass.value?.[2] : null,
    release: Number(taskType.value),
    subject: nowGlobalSubjectId.value,
    stage: nowGlobalStageId.value,
    school_id: authStore.userInfo.school_id
  }
  if (searchDate.value) {
    param.start_time = dayjs(searchDate.value).startOf('day').unix()
    param.end_time = dayjs(searchDate.value).endOf('day').unix()
  }
  if (param.release === 1) {
    param.role_code = authStore.nowGlobalRole.role_code
  }
  // taskList.value = []
  loading.value = true
  const res = await getTaskList(param)
  loading.value = false
  taskList.value = res.data?.list || []
  pageInfo.value.total = res.data?.total
}

// 重练标签展示
const getIsRetrainTag = task => {
  return (
    task.wrong_question_task?.retrain_time &&
    dayjs(task.wrong_question_task?.retrain_time).valueOf() <
      new Date().getTime()
  )
}

const toDetail = param => {
  // 数据埋点
  postCollect({
    action_type: 3,
    task_id: String(param.task_id)
  })

  let name = ''
  const query = {
    taskId: param.task_id,
    taskName: param.task_name,
    courseId: param.courseId
  }
  switch (true) {
    case param.task_type <= 3:
      name = 'courseDetail'
      break
    case param.task_type === 4:
      name = 'practiceDetail'
      break
  }
  if (taskType.value === '0') {
    router.push({
      name: 'waitDetail',
      query
    })
    return
  }
  router.push({
    name,
    query
  })
}

const getColor = task => {
  const rate = task.score_rate * 100
  if (Number(task.grade_count)) {
    if (rate >= 80) {
      return '#66c9f6'
    } else {
      return '#f9c581'
    }
  } else {
    return '#b7b8bb'
  }
}

const toCourse = () => {
  router.push({
    path: '/question-bank/ai-lesson/list'
  })
}
const toPractice = () => {
  router.push({
    path: '/question-bank/resource-center/topics'
  })
}

const isFinish = ref(false)
const onShowFinish = () => {
  isFinish.value = true
}

const toWrongScan = () => {
  router.push({
    name: 'wrongScan'
  })
}

const toCorrect = task => {
  if (task.status !== 1) return
  if (task.correct_type == CORRECT_TYPE.SCORE) {
    router.push({
      name: 'singleCorrect',
      query: {
        taskId: task.task_id
      }
    })
  } else {
    router.push({
      name: 'detailCorrect',
      query: {
        taskId: task.task_id,
        name: task.task_name,
        classList: JSON.stringify(
          task.class_info.map(item => ({
            classId: item.class_id,
            className: item.class_name,
            class_type: item.class_type
          }))
        )
      }
    })
  }
}

// 编辑待发布弹框
const taskVis = ref(false)
const editTaskId = ref(null)
const toEdit = task => {
  editTaskId.value = task.task_id
  taskVis.value = true
}
watch(taskVis, () => {
  if (!taskVis.value) {
    onSearch()
  }
})

onMounted(() => {
  searchDate.value = localStorage.getItem('taskFilterDate') || ''
  searchValue.value = localStorage.getItem('taskFilterSearch') || ''
  currentClass.value =
    (localStorage.getItem('taskFilterClass') &&
      JSON.parse(localStorage.getItem('taskFilterClass'))) ||
    []

  localStorage.removeItem('taskFilterDate')
  localStorage.removeItem('taskFilterSearch')
  localStorage.removeItem('taskFilterClass')
})

onUnmounted(() => {
  localStorage.setItem('taskFilterDate', searchDate.value || '')
  localStorage.setItem('taskFilterSearch', searchValue.value || '')
  localStorage.setItem(
    'taskFilterClass',
    JSON.stringify(currentClass.value) || ''
  )
})

watch(
  () => route,
  () => {
    taskType.value = null
    nextTick(() => {
      taskType.value = route.query?.type == 0 ? '0' : '1'
    })
  },
  { deep: true, immediate: true }
)
</script>

<style lang="less" scoped>
.assignment-container {
  .assignment-tabs {
    :deep(.el-tabs__nav-wrap) {
      &::after {
        height: unset;
      }
    }
  }
  .tool-btn {
    gap: 12px;

    :deep(.el-input) {
      width: 186px !important;
    }

    :deep(.el-input__inner) {
      font-size: 14px;
      &::placeholder {
        font-size: 14px;
      }
    }

    .search-btn {
      font-size: 14px;
    }
  }
  .content {
    background-color: #fff;
    padding: 20px;
    margin-top: 10px;
    margin-top: 20px;
    gap: 50px;
    align-items: unset;
    .icon-img {
      width: 18px;
    }

    .small-icon-img {
      width: 18px;
    }
    .title {
      font-weight: bold;
    }

    .content-left {
      width: 74%;

      .content-item {
        border-bottom: 1px solid hsl(60deg 9% 96%);
        padding-bottom: 20px;
        margin-bottom: 20px;

        .content-item-left {
          flex: 1;
          .title {
            gap: 10px;
            .task-name {
              width: 800px;
              font-size: @size-nav3;
              font-weight: bold;
            }
          }

          .info {
            margin-top: 12px;
            gap: 20px;

            .info-item {
              font-size: @size-base;
              gap: 10px;
            }
          }

          .tag {
            font-size: 16px;
            font-weight: 400;
            padding: 2px 4px;

            &.not-retrain {
              border: 1px solid #3333334d;
              color: #333;
              background-color: #fff;
            }

            &.retrained {
              border: 1px solid #faac37;
              color: #fff;
              background-color: #faac37;
            }
          }

          .el-tag--success {
            border: 1px solid #b7eb8f;
            border-radius: 4px;
            color: #52c41a;
            background: #f6ffed;
          }
        }

        .content-item-right {
          gap: 30px;
          align-items: self-start;

          .tip {
            height: 18px;
            .more-btn {
              margin-left: 10px;
            }
          }

          .right-1 {
            gap: 20px;

            .right-rate {
              text-align: center;
              line-height: 28px;
              height: 28px;
              font-size: 18px;
              font-weight: 700;
              margin-top: 10px;
            }
          }

          .right-2 {
            min-width: 110px;
            gap: 10px;

            .finish {
              display: flex;
              align-items: center;
              gap: 8px;
            }

            .right-2-btn-list {
              gap: 10px;
            }
          }

          .correct-btn {
            height: 28px;
            display: flex;
            align-items: center;

            .correct-icon {
              margin-right: 4px;
            }
          }
        }
      }
    }

    .content-right {
      margin-top: 2px;
      flex: 1;

      .title {
        margin-bottom: 20px;
        font-size: @size-nav1;
        font-weight: bold;
      }

      .btn-list {
        gap: 20px;

        .right-item {
          gap: 10px;

          .item-img {
            width: 60px;
          }
        }
      }
    }

    .border {
      width: 2px;
      background-color: #f5f1f0;
    }
  }
  /* stylelint-disable ebag/selector-class-pattern */
  :deep(.el-input__wrapper) {
    box-shadow: unset;
    color: #b7b8bb;
  }
}
</style>
<!-- eslint-disable -->
<style lang="less">
.task-class-search {
  .el-cascader-node__prefix {
    display: none;
  }

  .el-cascader-node__label {
    font-size: 14px;
  }

  .el-cascader-node {
    padding: 0 12px;
  }

  .el-cascader-menu {
    min-width: 140px;
  }
}
.delete-dialog {
  width: 400px;
}
</style>
